package com.sh.rbac.filter;

import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sh.rbac.domain.constant.CacheConstants;
import com.sh.rbac.domain.entity.LoginUser;
import com.sh.rbac.result.Result;
import com.sh.rbac.result.ResultCodeEnum;
import com.sh.rbac.utils.JwtUtils;
import com.sh.rbac.utils.WebUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * token 验证过滤器
 *
 * @since 2024-04-05 14:41
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 获取请求头中的token
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)) {
            //token不存在，交给其他过滤器处理
            chain.doFilter(request, response);
            return; //结束方法
        }

        // 判断是否是登录请求，例如判断请求路径是否为登录接口
        if ("/sys/user/login".equals(request.getRequestURI())) {
            // 是登录请求，跳过 token 验证
            chain.doFilter(request, response);
            return; // 结束方法
        }

        try {
            // 解密 token
            DecodedJWT decoded = JwtUtils.verifyToken(token);
            //Map<String, Claim> claims = decoded.getClaims();
            //userId = claims.get("id").asString();  // ID
        } catch (SignatureVerificationException e) {
            WebUtils.renderString(response, Result.failure(ResultCodeEnum.AUTH_SIGN_INVALID));
        } catch (TokenExpiredException e) {
            WebUtils.renderString(response, Result.failure(ResultCodeEnum.AUTH_TOKEN_EXPIRED));
        } catch (AlgorithmMismatchException e) {
            WebUtils.renderString(response, Result.failure(ResultCodeEnum.AUTH_ALG_INVALID));
        }

        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get(CacheConstants.USER_KEY + token);


        if (ObjectUtil.isNull(loginUser)) {
            WebUtils.renderString(response, Result.failure(ResultCodeEnum.AUTH_NOT_LOGIN));
        } else {

            // 封装用户权限
            Authentication authentication = new UsernamePasswordAuthenticationToken(
                    loginUser.getUser(), null, loginUser.getAuthorities());

            //将用户信息放入SecurityContext上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);

            chain.doFilter(request, response);
        }

    }
}
